package resman.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import resman.bean.LoginBean;
import resman.bean.ResumeBean;
import resman.database.DatabaseHandler;
import resman.database.TransSession;
import resman.model.ActionServlet;
import resman.model.UserStatus;

@SuppressWarnings("serial")
@WebServlet("/LoginServlet")
public class LoginServlet extends ActionServlet
{
	
	@Override
	protected void process(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException
	{
		TransSession tsession = DatabaseHandler.openSession(true);
		Session session = tsession.getSession();
		
		int op = getOpParameter("op", request);
		
		if (op == LOGIN_OP)
		{		
			LoginBean login = new LoginBean();
			login.setProperties(request.getParameterMap());
			
			if( login.getEmail().equals("admin@resman.com") && login.getPassword().equals("admin123"))
			{
				getSession(request).setAttribute("admin", "1");
			}	
			else
			{
				LoginBean result = (LoginBean) session.createQuery("from LoginBean " +
					"where email = :email and password = :password")
					.setParameter("email", login.getEmail())
					.setParameter("password", login.getPassword())
					.uniqueResult();
			
				if (result != null)
				{
					ResumeBean resume = result.getResume();
	
					if (resume.getLogin().getStatus() == UserStatus.ACTIVE)
					{
						setResume(resume, request);
						getSession(request).setAttribute("logged", "1");
						clearError(request);
					}
					else
						setError(request, "2");
				}
				else
					setError(request, "1");
			}
		}
		else
		{
			closeSession(request);
			getSession(request).setAttribute("logged", null);
			getSession(request).setAttribute("admin", null);
		}
			
		tsession.close();
		dispatchTo("index.jsp", request, response);
	}

}
